<template>
  <div class="content-card">
    <div class="page-header">
      <h2>订单列表</h2>
      <el-button type="primary" @click="handleExport">导出订单</el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="searchForm.userId" placeholder="请输入用户ID" />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择订单状态">
          <el-option label="全部" value="" />
          <el-option label="待支付" value="0" />
          <el-option label="待发货" value="1" />
          <el-option label="待收货" value="2" />
          <el-option label="已完成" value="3" />
          <el-option label="已取消" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式">
          <el-option label="全部" value="" />
          <el-option label="支付宝" value="1" />
          <el-option label="微信支付" value="2" />
          <el-option label="银行卡" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="timeRange">
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 订单表格 -->
    <el-table 
      v-loading="loading" 
      :data="orderList" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderNo" label="订单编号" min-width="180" />
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="userName" label="用户名" width="120" />
      <el-table-column prop="totalAmount" label="订单金额" width="100" formatter="formatPrice" />
      <el-table-column prop="paymentMethod" label="支付方式" width="120">
        <template #default="scope">
          {{ getPaymentMethodText(scope.row.paymentMethod) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderTime" label="下单时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleDetail(scope.row)">查看详情</el-button>
          <template v-if="scope.row.status === 1">
            <el-button size="small" @click="handleShip(scope.row)">发货</el-button>
          </template>
          <template v-if="scope.row.status === 0">
            <el-button size="small" type="danger" @click="handleCancel(scope.row.id)">取消</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <div class="pagination-info">
        共 {{ total }} 条记录，每页显示 {{ pageSize }} 条
      </div>
      <el-pagination 
        v-model:current-page="currentPage" 
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedOrders.length > 0">
      <el-button type="danger" @click="handleBatchCancel">批量取消</el-button>
      <el-button type="primary" @click="handleBatchShip">批量发货</el-button>
    </div>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderApi } from '../../api/order.js'

export default {
  name: 'OrderList',
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const orderList = ref([])
    const selectedOrders = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 搜索表单
    const searchForm = reactive({
      orderNo: '',
      userId: '',
      status: '',
      paymentMethod: '',
      timeRange: []
    })
    
    // 格式化价格
    const formatPrice = (row, column, cellValue) => {
      return `¥${cellValue.toFixed(2)}`
    }
    
    // 获取支付方式文本
    const getPaymentMethodText = (method) => {
      const methodMap = {
        1: '支付宝',
        2: '微信支付',
        3: '银行卡'
      }
      return methodMap[method] || '未知'
    }
    
    // 获取订单状态文本
    const getStatusText = (status) => {
      const statusMap = {
        0: '待支付',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知'
    }
    
    // 获取订单状态标签类型
    const getStatusTagType = (status) => {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'info',
        3: 'success',
        4: 'danger'
      }
      return typeMap[status] || 'default'
    }
    
    // 获取订单列表
    const getOrderList = async () => {
      loading.value = true
      try {
        const params = {
          ...searchForm,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 模拟API请求，使用mock数据
        setTimeout(() => {
          orderList.value = generateMockData()
          total.value = 100
          loading.value = false
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // const response = await orderApi.getOrderList(params)
        // orderList.value = response.data.list
        // total.value = response.data.total
        // loading.value = false
      } catch (error) {
        console.error('获取订单列表失败:', error)
        ElMessage.error('获取订单列表失败')
        loading.value = false
      }
    }
    
    // 生成模拟数据
    const generateMockData = () => {
      const orders = []
      
      for (let i = 0; i < pageSize.value; i++) {
        const index = (currentPage.value - 1) * pageSize.value + i + 1
        const status = Math.floor(Math.random() * 5)
        const paymentMethod = Math.floor(Math.random() * 3) + 1
        
        orders.push({
          id: index,
          orderNo: `ORD-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}-${String(index).padStart(4, '0')}`,
          userId: Math.floor(Math.random() * 10000) + 1,
          userName: `用户${Math.floor(Math.random() * 10000)}`,
          totalAmount: Math.floor(Math.random() * 5000) + 100,
          paymentMethod: paymentMethod,
          status: status,
          orderTime: new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)).toLocaleString()
        })
      }
      
      return orders
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getOrderList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        if (key === 'timeRange') {
          searchForm[key] = []
        } else {
          searchForm[key] = ''
        }
      })
      currentPage.value = 1
      getOrderList()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      getOrderList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      currentPage.value = current
      getOrderList()
    }
    
    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedOrders.value = selection
    }
    
    // 处理查看详情
    const handleDetail = (order) => {
      router.push(`/order/detail/${order.id}`)
    }
    
    // 处理发货
    const handleShip = async (order) => {
      try {
        // 模拟发货请求
        setTimeout(() => {
          ElMessage.success('发货成功')
          getOrderList()
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // await orderApi.shipOrder(order.id)
        // ElMessage.success('发货成功')
        // getOrderList()
      } catch (error) {
        console.error('发货失败:', error)
        ElMessage.error('发货失败')
      }
    }
    
    // 处理取消订单
    const handleCancel = async (id) => {
      ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 模拟取消请求
          setTimeout(() => {
            ElMessage.success('订单取消成功')
            getOrderList()
          }, 500)
          
          // 实际API调用代码（目前注释掉）
          // await orderApi.cancelOrder(id)
          // ElMessage.success('订单取消成功')
          // getOrderList()
        } catch (error) {
          console.error('取消订单失败:', error)
          ElMessage.error('取消订单失败')
        }
      }).catch(() => {
        // 取消操作
      })
    }
    
    // 处理批量取消
    const handleBatchCancel = () => {
      ElMessageBox.confirm(`确定要取消选中的 ${selectedOrders.value.length} 个订单吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = selectedOrders.value.map(order => order.id)
          // 模拟批量取消请求
          setTimeout(() => {
            ElMessage.success('批量取消成功')
            selectedOrders.value = []
            getOrderList()
          }, 500)
          
          // 实际API调用代码（目前注释掉）
          // await orderApi.batchCancelOrders(ids)
          // ElMessage.success('批量取消成功')
          // selectedOrders.value = []
          // getOrderList()
        } catch (error) {
          console.error('批量取消失败:', error)
          ElMessage.error('批量取消失败')
        }
      }).catch(() => {
        // 取消操作
      })
    }
    
    // 处理批量发货
    const handleBatchShip = async () => {
      // 检查选中的订单是否都可以发货
      const canShipOrders = selectedOrders.value.filter(order => order.status === 1)
      if (canShipOrders.length !== selectedOrders.value.length) {
        ElMessage.warning('请选择待发货状态的订单')
        return
      }
      
      try {
        const ids = selectedOrders.value.map(order => order.id)
        // 模拟批量发货请求
        setTimeout(() => {
          ElMessage.success('批量发货成功')
          selectedOrders.value = []
          getOrderList()
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // await orderApi.batchShipOrders(ids)
        // ElMessage.success('批量发货成功')
        // selectedOrders.value = []
        // getOrderList()
      } catch (error) {
        console.error('批量发货失败:', error)
        ElMessage.error('批量发货失败')
      }
    }
    
    // 处理导出订单
    const handleExport = async () => {
      try {
        // 模拟导出请求
        setTimeout(() => {
          ElMessage.success('订单导出成功')
        }, 1000)
        
        // 实际API调用代码（目前注释掉）
        // await orderApi.exportOrders(searchForm)
        // ElMessage.success('订单导出成功')
      } catch (error) {
        console.error('导出订单失败:', error)
        ElMessage.error('导出订单失败')
      }
    }
    
    // 初始化数据
    onMounted(() => {
      getOrderList()
    })
    
    return {
      loading,
      orderList,
      selectedOrders,
      total,
      currentPage,
      pageSize,
      searchForm,
      formatPrice,
      getPaymentMethodText,
      getStatusText,
      getStatusTagType,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleDetail,
      handleShip,
      handleCancel,
      handleBatchCancel,
      handleBatchShip,
      handleExport
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 15px;
  }
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  
  .pagination-info {
    color: var(--text-secondary);
    font-size: 14px;
  }
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  
  .el-button {
    margin-right: 10px;
  }
}
</style>